package com.atguigu.day10;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.*;
import org.apache.flink.types.Row;
import org.apache.kafka.clients.consumer.ConsumerConfig;

import static org.apache.flink.table.api.Expressions.$;

public class Flink05_Connect_Kafka_Source {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);



        //TODO 3.通过connector读取文件中的数据
        Schema schema = new Schema();
        schema.field("id", DataTypes.STRING());
        schema.field("ts", DataTypes.BIGINT());
        schema.field("vc", DataTypes.INT());


        tableEnv.connect(new Kafka()
                //一定要指定版本
                .version("universal")
        .property(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop102:9092")
                .topic("sensor")
                .property(ConsumerConfig.GROUP_ID_CONFIG, "0828")
                .startFromLatest()
        )
                .withSchema(schema)
                .withFormat(new Json())
                .createTemporaryTable("sensor");

        //通过表名获取到Table对象
        Table table = tableEnv.from("sensor");

        Table resultTable = table.where($("id").isEqual("sensor_1"))
                .select($("id"), $("ts"), $("vc"));

        //将表转为流
        tableEnv.toAppendStream(resultTable, Row.class).print();

        env.execute();

    }
}
